require 'json'

class Document
  def initialize(document_id)
    @document_id = document_id.to_s
    if @document_id.match('=>') || @document_id.match(';')
      raise Exception, "Invalid Document ID, please remove '=>' end ';'"
    else
      @document = {'document_id' => @document_id}
    end
  end
  
  def <<(other)
    if other.is_a?(Hash)
      other.delete('document_id') if other.has_key?('document_id')
    
      other.each_pair do |key, value|
        if value.is_a?(Document)
          other[key] = {'document_id' => value['document_id']}
        end
      end
      @document = @document.merge(other)
      return true
    end
    
    return false
  end
  
  def [](key)
    @document[key]
  end
  
  def []=(key, value)
    if key != 'document_id'
      @document[key] = value
    end
    
  end
  
  def clear
    @document = {'document_id' => @document_id}
  end
  
  def delete(key)
    @document.delete(key)
  end
  
  def has_value?(value)
    @document.has_value?(value)
  end
  
  def has_key?(key)
    @document.has_key?(key)
  end
  
  def to_h
    @document
  end
  
  def to_s
    @document.to_s
  end
  
  def to_json
    JSON.generate(@document)
  end
end
